<template>
  <div class="task-package-detail-page" v-if="taskPackage">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <el-button @click="$router.go(-1)" type="text">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2 class="page-title">任务包详情</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 任务包基本信息 -->
    <div class="package-info-section">
      <el-card class="package-info-card">
        <template #header>
          <div class="card-header">
            <span>任务包基本信息</span>
            <el-tag :type="getStatusType(taskPackage.status)" size="large">
              {{ getStatusText(taskPackage.status) }}
            </el-tag>
          </div>
        </template>
        
        <div class="package-basic-info">
          <div class="info-row">
            <div class="info-item">
              <span class="label">任务包编号：</span>
              <span class="value">{{ taskPackage.packageId }}</span>
            </div>
            <div class="info-item">
              <span class="label">配送区域：</span>
              <span class="value">{{ taskPackage.deliveryArea }}</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">配送时间：</span>
              <span class="value">{{ taskPackage.deliveryTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">预计距离：</span>
              <span class="value">{{ taskPackage.estimatedDistance }}公里</span>
            </div>
          </div>
          
          <div class="info-row">
            <div class="info-item">
              <span class="label">订单数量：</span>
              <span class="value">{{ taskPackage.orderCount }}个</span>
            </div>
            <div class="info-item">
              <span class="label">总配送费：</span>
              <span class="value reward">¥{{ taskPackage.totalReward }}</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 订单列表 -->
    <div class="orders-section">
      <el-card class="orders-card">
        <template #header>
          <div class="card-header">
            <span>包含订单列表</span>
            <div class="header-actions">
              <el-button type="primary" size="small" @click="startScanning">
                <el-icon><Camera /></el-icon>
                扫码取货
              </el-button>
              <el-button type="success" size="small" @click="startDelivery">
                <el-icon><Van /></el-icon>
                开始配送
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="orders-list">
          <div 
            v-for="(order, index) in taskPackage.orders" 
            :key="order.orderNumber"
            class="order-item"
            :class="{ 'current-order': currentOrderIndex === index }"
          >
            <div class="order-header">
              <div class="order-number">{{ order.orderNumber }}</div>
              <div class="order-status">
                <el-tag :type="getOrderStatusType(order.status)" size="small">
                  {{ getOrderStatusText(order.status) }}
                </el-tag>
              </div>
            </div>
            
            <div class="order-info">
              <div class="customer-info">
                <div class="info-row">
                  <span class="label">客户姓名：</span>
                  <span class="value">{{ order.customerName }}</span>
                </div>
                <div class="info-row">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ order.customerPhone }}</span>
                </div>
                <div class="info-row">
                  <span class="label">配送地址：</span>
                  <span class="value">{{ order.address }}</span>
                </div>
              </div>
              
              <div class="order-details">
                <div class="detail-item">
                  <span class="label">配送费：</span>
                  <span class="value">¥{{ order.reward }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">包裹数量：</span>
                  <span class="value">{{ order.packageCount || 1 }}个</span>
                </div>
                <div class="detail-item">
                  <span class="label">备注：</span>
                  <span class="value">{{ order.remark || '无' }}</span>
                </div>
              </div>
            </div>
            
            <div class="order-actions">
              <el-button 
                v-if="order.status === 0" 
                type="primary" 
                size="small" 
                @click="scanOrder(order)"
              >
                <el-icon><Camera /></el-icon>
                扫码取货
              </el-button>
              <el-button 
                v-if="order.status === 1" 
                type="success" 
                size="small" 
                @click="deliverOrder(order)"
              >
                <el-icon><Van /></el-icon>
                配送
              </el-button>
              <el-button 
                v-if="order.status === 2" 
                type="warning" 
                size="small" 
                @click="signOrderLocal(order)"
              >
                <el-icon><Check /></el-icon>
                签收
              </el-button>
              <el-button 
                type="info" 
                size="small" 
                @click="viewOrderDetail(order)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
              <el-button 
                type="warning" 
                size="small" 
                @click="reportExceptionLocal(order)"
              >
                <el-icon><Warning /></el-icon>
                异常
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 配送进度 -->
    <div class="delivery-progress-section">
      <el-card class="progress-card">
        <template #header>
          <span>配送进度</span>
        </template>
        
        <div class="progress-info">
          <div class="progress-stats">
            <div class="stat-item">
              <div class="stat-number">{{ completedCount }}</div>
              <div class="stat-label">已完成</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ deliveringCount }}</div>
              <div class="stat-label">配送中</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ pendingCount }}</div>
              <div class="stat-label">待配送</div>
            </div>
          </div>
          
          <el-progress 
            :percentage="progressPercentage" 
            :color="progressColor(progressPercentage)"
            :stroke-width="12"
          />
          
          <div class="progress-text">
            已完成 {{ completedCount }}/{{ taskPackage.orders.length }} 个订单
          </div>
        </div>
      </el-card>
    </div>

    <!-- 扫码对话框 -->
    <el-dialog
      v-model="scanDialogVisible"
      title="扫码取货"
      width="400px"
      class="scan-dialog"
    >
      <div class="scan-content">
        <div class="scan-area">
          <el-icon size="48" color="#409eff"><Camera /></el-icon>
          <p>请扫描包裹上的条码</p>
          <el-input
            v-model="scanCode"
            placeholder="手动输入条码"
            @keyup.enter="handleScan"
          />
        </div>
        
        <div class="scan-result" v-if="scanResult">
          <el-alert
            :title="scanResult.success ? '扫码成功' : '扫码失败'"
            :type="scanResult.success ? 'success' : 'error'"
            :description="scanResult.message"
            show-icon
          />
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="scanDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleScan">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="orderDetailVisible"
      title="订单详情"
      width="600px"
      class="order-detail-dialog"
    >
      <div class="order-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">
            {{ currentOrder.orderNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="客户姓名">
            {{ currentOrder.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentOrder.customerPhone }}
          </el-descriptions-item>
          <el-descriptions-item label="配送费">
            ¥{{ currentOrder.reward }}
          </el-descriptions-item>
          <el-descriptions-item label="配送地址" :span="2">
            {{ currentOrder.address }}
          </el-descriptions-item>
          <el-descriptions-item label="包裹数量">
            {{ currentOrder.packageCount || 1 }}个
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrder.status)" size="small">
              {{ getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ currentOrder.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 异常对话框 -->
    <el-dialog
      v-model="exceptionDialogVisible"
      title="上报异常"
      width="400px"
    >
      <el-form>
        <el-form-item label="客户名称">
          <el-input v-model="exceptionCustomer" disabled />
        </el-form-item>
        <el-form-item label="运单号">
          <el-input v-model="exceptionTrackingId" disabled />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-select v-model="exceptionType" placeholder="请选择异常类型">
            <el-option v-for="item in exTypeOptions" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度">
          <el-select v-model="exceptionSeverity" placeholder="请选择严重程度">
            <el-option v-for="item in exSeverityOptions" :key="item.code" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常描述">
          <el-input
            v-model="exceptionDesc"
            type="textarea"
            placeholder="请填写异常描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="异常图片">
          <el-upload
            v-model:file-list="exceptionImages"
            action=""
            :auto-upload="false"
            list-type="picture-card"
            :on-remove="handleRemoveImage"
            :on-change="handleImageChange"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="exceptionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitException">提交</el-button>
      </template>
    </el-dialog>
  </div>
  <div v-else class="page-loading">
    <el-icon class="is-loading" :size="32"><Loading /></el-icon>
    <span>正在加载任务包数据...</span>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElDialog, ElButton, ElCard, ElTag, ElIcon, ElProgress, ElInput, ElAlert, ElUpload } from 'element-plus'
import {
  ArrowLeft,
  Refresh,
  Camera,
  Van,
  Check,
  View,
  Warning,
  Loading,
  Plus
} from '@element-plus/icons-vue'
import { 
  getTaskPackageDetail, 
  acceptTaskPackage, 
  startTaskPackageDelivery, 
  completeTaskPackage,
  scanPackage,
  signOrder,
  reportException,
  uploadExceptionImage,
  getEXTypeList,
  getEXSeverity
} from '@/assets/delivery.js'

const route = useRoute()
const router = useRouter()

const taskPackage = ref(null)
const scanDialogVisible = ref(false)
const scanCode = ref('')
const scanResult = ref(null)
const currentOrderIndex = ref(-1)

// 订单详情相关
const orderDetailVisible = ref(false)
const currentOrder = ref({})

// 异常相关
const exceptionDialogVisible = ref(false)
const exceptionOrder = ref(null)
const exceptionType = ref('')
const exceptionDesc = ref('')
const exceptionImages = ref([])
const exceptionSeverity = ref('一般')
// 新增：异常类型和严重程度选项
const exTypeOptions = ref([])
const exSeverityOptions = ref([])

// 新增：回显用的表单字段
const exceptionCustomer = ref('')
const exceptionTrackingId = ref('')

// 数据获取
const fetchTaskPackageDetail = () => {
  const packageId = route.params.packageId
  if (!packageId) {
    ElMessage.error('无效的任务包ID')
    router.push('/delivery/home')
    return
  }
  
  taskPackage.value = null // 进入加载状态

  getTaskPackageDetail(packageId)
    .then(response => {
      const data = response.data.data
      if (response.data.code === 200 && data) {
        // 字段映射，保证页面字段都能正常显示
        taskPackage.value = {
          packageId: data.packageId,
          deliveryArea: data.destination, // 或 data.deliveryArea
          deliveryTime: data.startTime ? data.startTime.replace('T', ' ').slice(0, 16) : '',
          estimatedDistance: 5, // 你可以写死，或让后端返回
          orderCount: data.orders ? data.orders.length : 0,
          totalReward: data.orders ? data.orders.reduce((sum, o) => sum + (o.reward || 0), 0) : 0,
          orders: data.orders || [],
          status: data.deliveryStatus
        }
      } else {
        ElMessage.error(response.data.message || '获取任务包详情失败')
        router.push('/delivery/tasks/delivering')
      }
    })
    .catch(error => {
      console.error('获取任务包详情失败:', error)
      ElMessage.error('网络错误，获取任务包详情失败')
    })
}

onMounted(() => {
  fetchTaskPackageDetail()
  // 动态获取异常类型和严重程度选项
  getEXTypeList().then(res => {
    if (res.data && res.data.code === 200) {
      exTypeOptions.value = res.data.data
    }
  })
  getEXSeverity().then(res => {
    if (res.data && res.data.code === 200) {
      exSeverityOptions.value = res.data.data
    }
  })
})

// 计算属性
const completedCount = computed(() => taskPackage.value?.orders.filter(o => o.status === 2).length || 0)
const deliveringCount = computed(() => taskPackage.value?.orders.filter(o => o.status === 1).length || 0)
const pendingCount = computed(() => taskPackage.value?.orders.filter(o => o.status === 0).length || 0)

const progressPercentage = computed(() => {
  if (!taskPackage.value || taskPackage.value.orders.length === 0) return 0
  return Math.round((completedCount.value / taskPackage.value.orders.length) * 100)
})

const progressColor = (percentage) => {
  if (percentage < 30) return '#f56c6c'
  if (percentage < 70) return '#e6a23c'
  return '#67c23a'
}

// 状态相关方法
const getStatusType = (status) => {
  const types = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    0: '待分配',
    1: '待取货',
    2: '配送中',
    3: '已完成',
    4: '异常'
  }
  return texts[status] || '未知'
}

const getOrderStatusType = (status) => {
  const types = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'danger'
  }
  return types[status] || 'info'
}

const getOrderStatusText = (status) => {
  const texts = {
    0: '待取货',
    1: '配送中',
    2: '已送达',
    3: '异常'
  }
  return texts[status] || '未知'
}

// 方法
const handleRefresh = () => fetchTaskPackageDetail()
const startScanning = () => {
  scanDialogVisible.value = true
  scanCode.value = ''
  scanResult.value = null
}
const startDelivery = () => {
  // 跳转到导航页并传递地址
  router.push({
    path: '/delivery/routes/navigation',
    query: {
      address: taskPackage.value.deliveryArea // 或 destination 字段
    }
  })
}
const scanOrder = (order) => startScanning()
const handleScan = () => {
  // 实际项目中应调用API验证
  const order = taskPackage.value.orders.find(o => o.orderNumber === scanCode.value)
  if (order) {
    order.status = 1 // 模拟取货成功
    scanResult.value = { success: true, message: `订单 ${scanCode.value} 取货成功！` }
    setTimeout(() => { scanDialogVisible.value = false }, 1500)
  } else {
    scanResult.value = { success: false, message: `未在此任务包中找到订单 ${scanCode.value}` }
  }
}
const deliverOrder = (order) => ElMessage.success(`订单 ${order.orderNumber} 开始配送`)
const signOrderLocal = (order) => {
  order.status = 2 // 本地模拟签收
  ElMessage.success(`订单 ${order.orderNumber} 已签收`)
}
const viewOrderDetail = (order) => {
  currentOrder.value = { ...order }
  orderDetailVisible.value = true
}
const reportExceptionLocal = (order) => {
  exceptionOrder.value = order
  exceptionType.value = ''
  exceptionDesc.value = ''
  exceptionImages.value = []
  exceptionSeverity.value = '一般'
  // 回显客户名和运单号
  exceptionCustomer.value = order.customerName
  exceptionTrackingId.value = order.orderNumber
  exceptionDialogVisible.value = true
}
const handleRemoveImage = (file, fileList) => {
  exceptionImages.value = fileList
}
const handleImageChange = (file, fileList) => {
  exceptionImages.value = fileList
}
const submitException = async () => {
  if (!exceptionType.value) {
    ElMessage.warning('请选择异常类型')
    return
  }
  if (!exceptionSeverity.value) {
    ElMessage.warning('请选择严重程度')
    return
  }
  try {
    // 1. 先新建异常单
    const res = await reportException({
      trackingId: exceptionTrackingId.value,
      customer: exceptionCustomer.value,
      type: exceptionType.value,
      description: exceptionDesc.value,
      severity: exceptionSeverity.value
    })
    if (res.data && res.data.code === 200) {
      const reportId = res.data.data?.id || res.data.data?.reportId || res.data.data
      // 2. 上传所有图片
      for (const file of exceptionImages.value) {
        const formData = new FormData()
        formData.append('report_id', reportId)
        formData.append('image', file.raw)
        await uploadExceptionImage(formData)
      }
      ElMessage.success('异常上报成功')
      exceptionDialogVisible.value = false
      exceptionImages.value = []
      fetchTaskPackageDetail()
    } else {
      ElMessage.error(res.data.message || '异常上报失败')
    }
  } catch (e) {
    ElMessage.error('异常上报失败')
  }
}
</script>

<style scoped>
.task-package-detail-page {
  padding: 24px;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  min-height: 100vh;
}

/* 页面标题 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

/* 任务包信息 */
.package-info-section {
  margin-bottom: 24px;
}

.package-info-card {
  border: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.package-basic-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-row {
  display: flex;
  gap: 32px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  font-size: 14px;
  color: #6b7280;
  min-width: 80px;
}

.value {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.value.reward {
  color: #10b981;
}

/* 订单列表 */
.orders-section {
  margin-bottom: 24px;
}

.orders-card {
  border: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.header-actions {
  display: flex;
  gap: 8px;
}

.orders-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.order-item {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
  background: white;
}

.order-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-item.current-order {
  border-color: #10b981;
  background: #f0fdf4;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.order-number {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.order-info {
  display: flex;
  gap: 32px;
  margin-bottom: 16px;
}

.customer-info {
  flex: 1;
}

.info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.order-details {
  flex: 1;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.order-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 配送进度 */
.delivery-progress-section {
  margin-bottom: 24px;
}

.progress-card {
  border: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.progress-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  gap: 32px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #1f2937;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
}

.progress-text {
  text-align: center;
  font-size: 14px;
  color: #6b7280;
}

/* 扫码对话框 */
.scan-dialog :deep(.el-dialog) {
  border-radius: 16px;
}

.scan-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.scan-area {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  padding: 40px;
  background: #f8fafc;
  border-radius: 12px;
  border: 2px dashed #d1d5db;
}

.scan-area p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.scan-result {
  margin-top: 16px;
}

/* 订单详情对话框 */
.order-detail-dialog :deep(.el-dialog) {
  border-radius: 16px;
}

.order-detail {
  padding: 20px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .task-package-detail-page {
    padding: 16px;
  }
  
  .info-row {
    flex-direction: column;
    gap: 16px;
  }
  
  .order-info {
    flex-direction: column;
    gap: 16px;
  }
  
  .progress-stats {
    flex-direction: column;
    gap: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
}

.page-loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80vh;
  flex-direction: column;
  gap: 16px;
  color: #606266;
}
</style> 